const Router = require('koa-router');
const coBusboy = require('co-busboy');

const { auth } = require('./../utils');
const { message } = require('./../utils/xml2js');
const Wechat = require('./../wechat');

const router = new Router();
const wechat = new Wechat();

router
.get('/auth', async ctx => {

  const echostr = auth(ctx);
  if(echostr) {
    console.log('token验证成功');
    ctx.body = echostr;
  } else {// 验证失败
    console.log('token验证失败');
    ctx.body = '';
  }
})
.post('/auth', async ctx => {

  // {
  //   ToUserName,// 开发者微信号
  //   FromUserName,// 发送方openid
  //   CreateTime,// 消息创建时间
  //   MsgType,// 消息类型
  //   Content,// text内容
  //   MsgId// 消息id
  // }

  const xml = ctx.req.body.xml;
  ctx.res.setHeader('Content-Type', 'application/xml');
  ctx.res.end(message.text(xml, '你说了：' + xml.Content));
})
.get('/', async ctx => ctx.redirect('/app.html'))
.post('/uploadMediaImg', async ctx => {

  if(ctx.is('multipart')) {

    wechat.uploadMediaImg(ctx.request.files.file)
      .then(response => {
        console.log(response.data)
      }).catch(err => console.log(err));

    ctx.body = {
      retCode: 0,
      msg: 'suc',
    }
  } else {

    ctx.body = {
      retCode: -1,
      msg: '不是multipart',
    }
  }
})
.post('/sendMessage', async ctx => {

  wechat.sendMessage()
    .catch(err => console.log(err))

  ctx.body = {
    retCode: 0,
    msg: 'suc',
  }
})
.post('/uploadMedia', async ctx => {

  if(ctx.is('multipart')) {

    wechat.uploadMedia(ctx.request.files.file, 'thumb')
      .then(response => {
        console.log(response.data)
      }).catch(err => console.log(err));

    ctx.body = {
      retCode: 0,
      msg: 'suc',
    }
  } else {

    ctx.body = {
      retCode: -1,
      msg: '不是multipart',
    }
  }
})
.post('/addMaterial', async ctx => {

  if(ctx.is('multipart')) {

    wechat.addMaterial(ctx.request.files.file, 'thumb')
      .then(response => {
        console.log(response.data)
      }).catch(err => console.log(err));

    ctx.body = {
      retCode: 0,
      msg: 'suc',
    }
  } else {

    ctx.body = {
      retCode: -1,
      msg: '不是multipart',
    }
  }
})
.post('/uploadMediaNews', async ctx => {

  wechat.uploadMediaNews()
    .then(response => {
      console.log(response.data)
    }).catch(err => console.log(err));

  ctx.body = {
    retCode: 0,
    msg: 'suc',
  }
})

module.exports = router;